﻿
var tableToExcel = (function () {
    var uri = 'data:application/vnd.ms-excel;base64,'
      , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
      , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))); }
      , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }); };
    return function (tableOri) {
        
        var $table = $('<table/>');
        var $trHead = $('<tr/>');
        
        //add rows
        var foundFirstTh;
        $("#" + tableOri + " tr").each(function () {
            var $tr = $('<tr/>');
            var columnCount = $(this).find('th').length;
            
            // row head, insert at firt row
            if (!foundFirstTh) {
                $(this).find('th').each(function () {
                    var $td = $('<td>' + $(this).text().replace('(less)', '') + '</td>');
                    $trHead.append($td);
                    foundFirstTh = true;
                });
                $trHead.find("th:last-child, td:last-child").remove();
                $table.prepend($trHead);
            }
            
            // row data
            $(this).find('td').each(function() {
                var colIndex = $(this).parent().children().index($(this));
                var rowIndex = $(this).parent().parent().children().index($(this).parent());
                 if ( !$(this).text().match(/(…more)/)) {
                    var $td = $('<td>' +  $(this).text().replace('(less)', '') +  '</td>');
                    $tr.append($td); 
                 } 
            });
            
            $tr.find("th:last-child, td:last-child").remove();
            if ($tr.find('td').length > 0) {
                $table.append($tr);
            }
        });
        
        $table.find('tr td:first-child').remove();


        // Find title
        var title = '';
        try {
            title = $("title").text().substr(0, $("title").text().indexOf('-') - 1);
        } catch (e) {
        }
        if (!title) {
            title = '';
        }
        var ctx = { worksheet: title || 'Worksheet', table: $table.html() };
        var formatted = format(template, ctx);
        window.location.href = uri + base64(formatted);
    };
})();

var tableToWord = (function () {
    var uri = 'data:application/msword;base64,'
      , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40"><body>{title}<table style="border:solid 1px black;border-collapse:collapse;"  border="1" cellpadding="0" cellspacing="0" >{table}</table></body></html>'
      , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))); }
      , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }); };
    return function (tableOri) {

        var $table = $('<table/>');
        var $trHead = $('<tr/>');
        
        //add rows
        var foundFirstTh;
        $("#" + tableOri + " tr").each(function () {
            var $tr = $('<tr/>');
            var columnCount = $(this).find('th').length;

            // row head, insert at firt row
            if (!foundFirstTh) {
                $(this).find('th').each(function () {
                    var $td = $('<td>' + $(this).text().replace('(less)', '') + '</td>');
                    $trHead.append($td);
                    foundFirstTh = true;
                });
                $trHead.find("th:last-child, td:last-child").remove();
                $table.prepend($trHead);
            }

            // row data
            $(this).find('td').each(function () {
                var colIndex = $(this).parent().children().index($(this));
                var rowIndex = $(this).parent().parent().children().index($(this).parent());
                if (!$(this).text().match(/(…more)/)) {
                    var $td = $('<td>' + $(this).text().replace('(less)', '') + '</td>');
                    $tr.append($td);
                }
            });

            $tr.find("th:last-child, td:last-child").remove();
            if ($tr.find('td').length > 0) {
                $table.append($tr);
            }
        });
        
        $table.find('tr td:first-child').remove();
        
        // Find title
        var title = '';
        try {
            title = $("title").text().substr(0, $("title").text().indexOf('-') - 1);
        } catch (e) {
        }
        if (!title) {
            title = '';
        }
        
        // Bind title at first line of ducument
        var ctx = { table: $table.html(), title: title };
        
        // Send to user
        var formatted = format(template, ctx);
        window.location.href = uri + base64(formatted);
    };
})();

function gerpUtility() {
	
	this.testValue = "field testValue in class gerpUtility";
	
	this.convertStringToDate = function (dateStr) {
	    if (dateStr == "") {
	        return new Date();
	    }
		var rawStr1 = dateStr.split("/");
		var rawStr2 = rawStr1[2].split(" ");
		rawStr1[2] = rawStr2[0];
		var day = rawStr1[0];
		var month = rawStr1[1];
		var year = rawStr1[2];

		var result = new Date(this.getJsYear(year), this.getJsMonth(month), day);
		return result;
	};
	
	this.paddingNumber = function (n, width, z) {
		z = z || '0';
		n = n + '';
		return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
	};
	
	this.getDayOfWeekWord = function (d) {

		var weekday = new Array(7);
		weekday[0] = "Sunday";
		weekday[1] = "Monday";
		weekday[2] = "Tuesday";
		weekday[3] = "Wednesday";
		weekday[4] = "Thursday";
		weekday[5] = "Friday";
		weekday[6] = "Saturday";

		return weekday[d.getDay()];
	};
	
	this.getDatePickerStringFormat = function (d) {
		return this.paddingNumber(d.getDate(), 2, 0) + "/" +
			this.paddingNumber(this.getMonth(d), 2, 0) + "/" + this.getYear(d);
	};
	
	this.getMonth = function (d) {
		return d.getMonth() + 1;
	};
	
	this.getYear = function (d) {
		return d.getFullYear() + 543;
	};
	
	this.getJsMonth = function (numberMonth) {
		return numberMonth - 1;
	};
	
	this.getJsYear = function (numberYear) {
		if (numberYear.length == 2) numberYear = "25" + numberYear;
		else if (numberYear < 2400) numberYear = numberYear + 543;
		return numberYear - 543;
	};
     
} Array.prototype.inArray = function (comparer) {
    for (var i = 0; i < this.length; i++) {
        if (comparer(this[i])) return true;
    }
    return false;
};

// adds an element to the array if it does not already exist using a comparer 
// function
Array.prototype.pushIfNotExist = function (element, comparer) {
    if (!this.inArray(comparer)) {
        this.push(element);
    }
};